//
//  InfoUIM.m
//  mbstore
//
//  Created by huangyi on 14-3-12.
//  Copyright (c) 2014年 huangyi. All rights reserved.
//

#import "InfoUIM.h"

@interface InfoUIM ()

@property(nonatomic,weak)IBOutlet UIScrollView *itemScrollView;
@property(nonatomic,weak)IBOutlet UIImageView *itemImage;
@property(nonatomic,weak)IBOutlet UITextView *itemName;
@property(nonatomic,weak)IBOutlet UITextView *itemNumber;
@property(nonatomic,weak)IBOutlet UILabel *itemPrice;
@property(nonatomic,weak)IBOutlet UIScrollView *colorScrollView;
@property(nonatomic,weak)IBOutlet UIScrollView *sizeScrollView;
@property(nonatomic,weak)IBOutlet UILabel *itemStock;
@property(nonatomic,weak)IBOutlet UIButton *buyButton;
@property(nonatomic,weak)IBOutlet UIButton *closeButton;

@property(nonatomic,strong)NSMutableDictionary *sku;

@end

@implementation InfoUIM

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.modalPresentationStyle=UIModalPresentationFormSheet;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.sku=[NSMutableDictionary dictionary];

    [self.closeButton setImage:[UIImage imageNamed:@"media.bundle/close.png"] forState:UIControlStateNormal];
    [self.buyButton setBackgroundImage:[UIImage imageNamed:@"media.bundle/buy.png"] forState:UIControlStateNormal];
    [self.buyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setItemId:(NSString *)itemId{
    int idx=0;
    for (int i=0; i<self.items.count; i++) {
        NSString *obj=[self.items objectAtIndex:i];
        if ([obj isEqualToString:itemId]) {
            idx=i;
        }
    }
    int en=0;
    for (UIView *view in self.itemScrollView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *button=(id)view;
            UIView *line=[button viewWithTag:1001];
            if (line) {
                if (idx==en) {
                    line.hidden=NO;
                }else{
                    line.hidden=YES;
                }
                en++;
            }
        }
    }
  #warning 调用数据库
    NSDictionary *item=[AppUI getProductDict:itemId];
    _itemId=item[@"item_id"];
    self.sku[@"color_name"]=item[@"color_name"];

    self.itemName.text=item[@"name"];
    self.itemNumber.text=[NSString stringWithFormat:@"商品编号：%@",item[@"item_id"]];
    self.itemPrice.text=[NSString stringWithFormat:@"¥%@",item[@"price"]];
    NSString *imageName =item[@"main_photo"];
    imageName = [imageName stringByDeletingPathExtension];
    imageName = [NSString stringWithFormat:@"%@--w_320_h_320.jpg",imageName];
    NSString *imageURL=[AppUI getImageURL:imageName];
    [self.itemImage setImageURL:imageURL];
    self.itemStock.text=@"...";

    self.buyButton.enabled=NO;
    [self setColorAndSize];
}
-(void)setItems:(NSArray *)items{
    _items=items;
    [self.itemScrollView removeAllSubviews];
    for (int i=0; i<items.count; i++) {
        NSString *itemId=[items objectAtIndex:i];
          #warning 调用数据库
        NSDictionary *item=[AppUI getProductDict:itemId];
        UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
        button.tag=i;
        button.frame=CGRectMake(150*i, 0, 150, 50);
        UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(27, 2, 46, 46)];
        NSString *imageName =item[@"main_photo"];
        imageName = [imageName stringByDeletingPathExtension];
        imageName = [NSString stringWithFormat:@"%@--w_100_h_100.jpg",imageName];
        NSString *imageURL=[AppUI getImageURL:imageName];
        [imageView setImageURL:imageURL];
        [button addSubview:imageView];
        UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(77, 2, 46, 46)];
        label.textAlignment=NSTextAlignmentCenter;
        label.text=item[@"category"];
        label.textColor=[UIColor darkGrayColor];
        [button addSubview:label];
        [self.itemScrollView addSubview:button];
        [button addTarget:self action:@selector(onItemClick:) forControlEvents:UIControlEventTouchUpInside];
        UIView *line=[[UIView alloc] initWithFrame:CGRectMake(10, 47, 130, 3)];
        line.backgroundColor=[UIColor blackColor];
        [button addSubview:line];
        line.tag=1001;
        line.hidden=YES;
        int width=MAX(CGRectGetWidth(self.itemScrollView.frame), CGRectGetMaxX(button.frame));
        self.itemScrollView.contentSize=CGSizeMake(width, 50);
    }
}
-(void)setColorAndSize{
    [self.colorScrollView removeAllSubviews];
    [self.sizeScrollView removeAllSubviews];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        #warning 调用数据库
        NSArray *skus=[AppUI getProductSku:self.itemId];
        NSMutableArray *colorArray=[NSMutableArray array];
        NSMutableArray *sizeArray=[NSMutableArray array];
        NSMutableDictionary *colors=[NSMutableDictionary dictionary];
        NSMutableDictionary *sizes=[NSMutableDictionary dictionary];
        for (NSDictionary *sku in skus) {
            NSString *color=sku[@"color_name"];
            NSString *size=sku[@"size_name"];
            if (!colors[color]) {
                colors[color]=sku;
                [colorArray addObject:sku];
            }
            if (!sizes[size]) {
                sizes[size]=sku;
                [sizeArray addObject:sku];
            }
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                int sz=0;
                UIButton *sb=nil;
                for (NSDictionary *sku in sizeArray) {
                    UIButton *button=[self sizeButton:sku];
                    button.frame=CGRectOffset(button.bounds, (10+CGRectGetWidth(button.bounds))*sz, 0);
                    [self.sizeScrollView addSubview:button];
                    self.sizeScrollView.contentSize=CGSizeMake(CGRectGetMaxX(button.frame), CGRectGetHeight(button.frame));
                    if ([sizeArray indexOfObject:sku]==0) {
                        sb=button;
                    }
                    sz++;
                }
                [self onSizeClick:sb];
            });
            dispatch_async(dispatch_get_main_queue(), ^{
                int cz=0;
                UIButton *cb=nil;
                for (NSDictionary *sku in colorArray) {
                    UIButton *button=[self colorButton:sku];
                    button.frame=CGRectOffset(button.bounds, (10+CGRectGetWidth(button.bounds))*cz, 0);
                    [self.colorScrollView addSubview:button];
                    self.colorScrollView.contentSize=CGSizeMake(CGRectGetMaxX(button.frame), CGRectGetHeight(button.frame));
                    if ([sku[@"color_name"] isEqualToString:self.sku[@"color_name"]]) {
                        cb=button;
                    }
                    cz++;
                }
                [self onColorClick:cb];
            });
        });
    });
}

-(void)onItemClick:(id)sender{
    UIView *view=sender;
    int idx=view.tag;
    NSString *itemId=[self.items objectAtIndex:idx];
    self.itemId=itemId;
}

-(IBAction)onCloseClick:(id)sender{
    [self HideChild];
//    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)HideChild{
    [self willMoveToParentViewController:nil];
    [UIView animateWithDuration:0.3 animations:^{
       self.view.frame=CGRectMake(0, 1024, self.view.frame.size.width, self.view.frame.size.height);
    } completion:^(BOOL finished) {
        [self removeFromParentViewController];
        [self.view removeFromSuperview];
    }];
    
}
-(IBAction)onBuyClick:(id)sender{

    NSString *skuId=[self getSkuId];
    MainApp *app=[MainApp mainApp];
    [app.shoppingList addObject:skuId];
    [app requestProduct:skuId];
    [[NSNotificationCenter defaultCenter] postNotificationName:ShoppingListNotification object:self];
    
    MBProgressHUD *hud=[[MBProgressHUD alloc] initWithView:self.view];
    hud.mode=MBProgressHUDModeText;
    hud.labelText=@"成功添加到购物车";
    [self.view addSubview:hud];
    [hud show:YES];
    [hud hide:YES afterDelay:1.0];
}

-(UIButton*)colorButton:(NSDictionary*)sku{
    NSString *color=sku[@"color_name"];
    NSString *image=sku[@"main_photo"];
    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
    button.payloadObject=sku;
    [button addTarget:self action:@selector(onColorClick:) forControlEvents:UIControlEventTouchUpInside];
    button.frame=CGRectMake(0, 0, 50, 60);
    [button setTitle:color forState:UIControlStateNormal];
    [button setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    button.titleLabel.font=[UIFont systemFontOfSize:12];
    UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(5, 0, 40, 40)];
    imageView.tag=1001;
    [button addSubview:imageView];
    image = [image stringByDeletingPathExtension];
    image = [NSString stringWithFormat:@"%@--w_40_h_40.jpg",image];
    NSString *imageURL=[AppUI getImageURL:image];
    [imageView setImageURL:imageURL];
    return button;
}
-(void)onColorClick:(id)sender{
    for (id view in self.colorScrollView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *button=view;
            if (button==sender) {
                UIView *view=[button viewWithTag:1001];
                view.layer.borderColor=[[UIColor redColor] CGColor];
                view.layer.borderWidth=1;
                self.sku[@"color_name"]=button.payloadObject[@"color_name"];
                NSString *imageName =button.payloadObject[@"main_photo"];
                imageName = [imageName stringByDeletingPathExtension];
                imageName = [NSString stringWithFormat:@"%@--w_320_h_320.jpg",imageName];
                NSString *imageURL=[AppUI getImageURL:imageName];
                self.itemImage.image = nil;
                [self.itemImage setImageURL:imageURL];
            }else{
                UIView *view=[button viewWithTag:1001];
                view.layer.borderColor=[[UIColor grayColor] CGColor];
                view.layer.borderWidth=1;
            }
        }
    }
    [self checkStock];
}

-(UIButton*)sizeButton:(NSDictionary*)sku{
    NSString *size=sku[@"size_name"];
    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
    button.payloadObject=sku;
    [button addTarget:self action:@selector(onSizeClick:) forControlEvents:UIControlEventTouchUpInside];
    button.frame=CGRectMake(0, 0, 60, 20);
    [button setTitle:size forState:UIControlStateNormal];
    [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    button.titleLabel.font=[UIFont systemFontOfSize:12];
    return button;
}
-(void)onSizeClick:(id)sender{
    for (id view in self.sizeScrollView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *button=view;
            if (button==sender) {
                button.layer.borderColor=[[UIColor redColor] CGColor];
                button.layer.borderWidth=1;
                self.sku[@"size_name"]=button.payloadObject[@"size_name"];
            }else{
                button.layer.borderColor=[[UIColor grayColor] CGColor];
                button.layer.borderWidth=1;
            }
        }
    }
    [self checkStock];
}

-(NSString*)getSkuId{
    NSString *color=self.sku[@"color_name"];
    NSString *size=self.sku[@"size_name"];
    if (!color) {
        return nil;
    }
    if (!size) {
        return nil;
    }
    NSString *colorAndSize=[NSString stringWithFormat:@"%@;%@",color,size];
#warning 调用数据库
    NSString *skuId=[AppUI getSkuId:colorAndSize forItem:self.itemId];
    return skuId;
}
#warning TODO: 库存
//在点击颜色或尺码按钮后，发送sku查询，建立dispatch线程处理网络请求，并回到main线程更新视图
-(void)checkStock{
    NSString *skuId=[self getSkuId];
    if (!skuId) {
        self.buyButton.enabled=NO;
        self.itemStock.text=@"没有这组颜色尺码";
        return;
    }else{
        self.buyButton.enabled=YES;
        self.itemStock.text=@"查询库存中...";
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            HTTPClient *client=[AppUI getStock:skuId];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (client.error) {
                    self.itemStock.text=[NSString stringWithFormat:@"查询库存失败"];
                }else{
                    NSDictionary *response=[client.responseData JSONObject];
                    if ([[response valueForKeyPath:@"Result"] intValue]==1) {
                        NSArray *array=[response valueForKeyPath:@"Stocks"];
                        if (array.count) {
                            NSDictionary *dict=[array firstObject];
                            int count=[[dict valueForKeyPath:@"HandStock"] intValue];
                            if (count>0) {
                                self.itemStock.text=[NSString stringWithFormat:@"库存还剩 %@ 件",@(count)];
                            }else{
                                self.itemStock.text=[NSString stringWithFormat:@"没有库存了"];
                            }
                        }else{
                            self.itemStock.text=[NSString stringWithFormat:@"没有此商品"];
                        }
                    }else{
                        self.itemStock.text=[NSString stringWithFormat:@"查询库存失败"];
                    }
                }
            });
        });
    }
}

@end
